/* eslint-disable */
<template>
  <!-- 教师管理页面容器 -->
  <div class="teachers-container">
    <!-- 页面标题和工具栏 -->
    <div class="page-header">
      <h2>教师管理</h2>
      <!-- 工具栏：包含搜索框和添加教师按钮 -->
      <div class="toolbar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索教师"
          prefix-icon="el-icon-search"
          clearable
          style="width: 220px; margin-right: 10px;">
        </el-input>
        <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">添加教师</el-button>
      </div>
    </div>

    <!-- 过滤器：按院系筛选 -->
    <div class="filter-box">
      <span class="filter-label">院系筛选：</span>
      <el-select 
        v-model="deptFilter" 
        placeholder="选择院系" 
        clearable 
        @change="handleDeptChange" 
        style="width: 250px;">
        <el-option
          v-for="dept in departments"
          :key="dept.deptNumber"
          :label="dept.deptName"
          :value="dept.deptNumber">
        </el-option>
      </el-select>
    </div>

    <!-- 教师列表表格 -->
    <el-table 
      :data="filteredTeachers" 
      style="width: 100%" 
      border 
      stripe 
      v-loading="loading"
      element-loading-text="加载教师数据中...">
      <!-- 工号列 -->
      <el-table-column prop="teacherId" label="工号" width="120" align="center"></el-table-column>
      <!-- 姓名列 -->
      <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
      <!-- 性别列 -->
      <el-table-column prop="gender" label="性别" width="80" align="center"></el-table-column>
      <!-- 职称列 -->
      <el-table-column prop="title" label="职称" width="100" align="center"></el-table-column>
      <!-- 所属院系列 -->
      <el-table-column label="所属院系" min-width="150" align="center">
        <template slot-scope="scope">
          {{ getDepartmentName(scope.row.deptNumber) }}
        </template>
      </el-table-column>
      <!-- 电话列 -->
      <el-table-column prop="phone" label="电话" width="130" align="center"></el-table-column>
      <!-- 邮箱列 -->
      <el-table-column prop="email" label="邮箱" min-width="180" align="center"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTeachers.length">
      </el-pagination>
    </div>

    <!-- 添加/编辑教师对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog.visible" width="600px" :close-on-click-modal="false">
      <el-form :model="teacherForm" :rules="teacherRules" ref="teacherForm" label-width="100px" class="teacher-form">
        <!-- 工号输入框（仅在编辑模式下显示，且不可编辑） -->
        <el-form-item label="工号" prop="teacherId" v-if="dialog.type === 'edit'">
          <el-input v-model="teacherForm.teacherId" disabled></el-input>
        </el-form-item>
        
        <!-- 姓名输入框 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入教师姓名"></el-input>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 性别选择框 -->
            <el-form-item label="性别" prop="gender">
              <el-select v-model="teacherForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 职称选择框 -->
            <el-form-item label="职称" prop="title">
              <el-select v-model="teacherForm.title" placeholder="请选择职称" style="width: 100%">
                <el-option label="教授" value="教授"></el-option>
                <el-option label="副教授" value="副教授"></el-option>
                <el-option label="讲师" value="讲师"></el-option>
                <el-option label="助教" value="助教"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <!-- 所属院系选择框 -->
            <el-form-item label="所属院系" prop="deptNumber">
              <el-select 
                v-model="teacherForm.deptNumber" 
                placeholder="请选择所属院系" 
                style="width: 100%"
                @change="handleDeptSelect">
                <el-option
                  v-for="dept in departments"
                  :key="dept.deptNumber"
                  :label="dept.deptName"
                  :value="dept.deptNumber">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 电话输入框 -->
            <el-form-item label="电话" prop="phone">
              <el-input v-model="teacherForm.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 邮箱输入框 -->
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="teacherForm.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 添加时才显示密码输入框 -->
        <el-row :gutter="20" v-if="dialog.type === 'add'">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="teacherForm.password" type="password" placeholder="请输入登录密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="teacherForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 在添加模式下显示自动生成的工号提示 -->
        <el-row :gutter="20" v-if="dialog.type === 'add' && teacherForm.deptNumber">
          <el-col :span="24">
            <div class="teacher-id-hint">
              <i class="el-icon-info"></i>
              <span>教师工号将自动生成为: <strong>{{ previewTeacherId }}</strong></span>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" :visible.sync="passwordDialog.visible" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleResetPassword" :loading="passwordDialog.loading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAllTeachers, 
  getTeachersByDepartment,
  addTeacher,
  updateTeacher,
  deleteTeacher,
  updateTeacherPassword,
  getAllDepartments
} from '@/api/admin'

export default {
  name: 'TeacherManagement',
  data() {
    // 自定义验证器：确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.teacherForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    // 确认重置密码
    const validateResetPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      // 加载状态
      loading: false,
      submitLoading: false,
      // 搜索关键词
      searchQuery: '',
      // 院系筛选
      deptFilter: '',
      // 教师列表数据
      teachers: [],
      // 院系列表数据
      departments: [],
      // 对话框数据
      dialog: {
        visible: false,
        type: 'add' // 'add' 或 'edit'
      },
      // 教师表单数据
      teacherForm: {
        teacherId: '',
        name: '',
        gender: '',
        deptNumber: '',
        title: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: ''
      },
      // 教师数量统计（按院系）
      deptTeacherCounts: {},
      // 表单验证规则
      teacherRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        deptNumber: [
          { required: true, message: '请选择所属院系', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请选择职称', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 密码重置对话框
      passwordDialog: {
        visible: false,
        loading: false,
        teacherId: ''
      },
      // 密码重置表单
      passwordForm: {
        newPassword: '',
        confirmPassword: ''
      },
      // 密码重置验证规则
      passwordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateResetPassword, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 根据搜索关键词过滤教师列表
    filteredTeachers() {
      if (!this.teachers.length) return []
      
      let result = this.teachers
      
      // 院系筛选
      if (this.deptFilter) {
        result = result.filter(teacher => teacher.deptNumber === this.deptFilter)
      }
      
      // 关键字搜索
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(teacher => 
          teacher.teacherId.toLowerCase().includes(query) ||
          teacher.name.toLowerCase().includes(query) ||
          (teacher.email && teacher.email.toLowerCase().includes(query)) ||
          (teacher.phone && teacher.phone.includes(query))
        )
      }
      
      return result
    },
    // 对话框标题
    dialogTitle() {
      return this.dialog.type === 'add' ? '添加教师' : '编辑教师'
    },
    // 预览生成的教师工号（院系编号+教师数量）
    previewTeacherId() {
      if (!this.teacherForm.deptNumber) return ''
      
      const deptNumber = this.teacherForm.deptNumber
      const count = this.deptTeacherCounts[deptNumber] || 0
      
      // 返回院系编号 + 教师数量（格式化为3位数）
      return `${deptNumber}${(count + 1).toString().padStart(3, '0')}`
    }
  },
  created() {
    // 获取院系列表
    this.fetchDepartments()
    
    // 获取教师列表
    this.fetchTeachers()
  },
  methods: {
    // 获取院系列表
    fetchDepartments() {
      getAllDepartments().then(response => {
        const { data } = response
        if (data) {
          this.departments = data
        }
      }).catch(error => {
        console.error('获取院系列表失败:', error)
        this.$message.error('获取院系列表失败')
      })
    },
    
    // 获取所有教师
    fetchTeachers() {
      this.loading = true
      
      getAllTeachers().then(response => {
        const { data } = response
        if (data) {
          this.teachers = data
          // 计算每个院系的教师数量
          this.countTeachersByDept()
        }
      }).catch(error => {
        console.error('获取教师列表失败:', error)
        this.$message.error('获取教师列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 根据院系获取教师
    fetchTeachersByDept(deptNumber) {
      this.loading = true
      
      getTeachersByDepartment(deptNumber).then(response => {
        const { data } = response
        if (data) {
          this.teachers = data
        }
      }).catch(error => {
        console.error('获取院系教师失败:', error)
        this.$message.error('获取院系教师失败')
      }).finally(() => {
        this.loading = false
      })
    },
    
    // 处理院系筛选变化
    handleDeptChange(value) {
      if (value) {
        // 根据院系获取教师
        this.fetchTeachersByDept(value)
      } else {
        // 获取所有教师
        this.fetchTeachers()
      }
    },
    
    // 计算每个院系的教师数量
    countTeachersByDept() {
      const counts = {}
      
      // 初始化所有院系的计数为0
      this.departments.forEach(dept => {
        counts[dept.deptNumber] = 0
      })
      
      // 统计每个院系的教师数量
      this.teachers.forEach(teacher => {
        if (teacher.deptNumber) {
          counts[teacher.deptNumber] = (counts[teacher.deptNumber] || 0) + 1
        }
      })
      
      this.deptTeacherCounts = counts
    },
    
    // 处理院系选择改变
    handleDeptSelect() {
      // 当用户选择院系时，工号预览会自动更新
      console.log('院系已选择，工号将自动生成')
    },
    
    // 获取院系名称
    getDepartmentName(deptNumber) {
      const dept = this.departments.find(d => d.deptNumber === deptNumber)
      return dept ? dept.deptName : deptNumber
    },
    
    // 处理页大小变化
    handleSizeChange(size) {
      this.pageSize = size
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.currentPage = page
    },
    
    // 显示添加教师对话框
    showAddDialog() {
      this.dialog.type = 'add'
      this.teacherForm = {
        teacherId: '',
        name: '',
        gender: '',
        deptNumber: '',
        title: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: ''
      }
      this.$nextTick(() => {
        this.$refs.teacherForm && this.$refs.teacherForm.clearValidate()
      })
      this.dialog.visible = true
    },
    
    // 处理编辑教师
    handleEdit(teacher) {
      this.dialog.type = 'edit'
      this.teacherForm = { ...teacher }
      delete this.teacherForm.password
      delete this.teacherForm.confirmPassword
      
      this.$nextTick(() => {
        this.$refs.teacherForm && this.$refs.teacherForm.clearValidate()
      })
      this.dialog.visible = true
    },
    
    // 处理删除教师
    handleDelete(teacher) {
      this.$confirm(`确认删除教师 "${teacher.name}(${teacher.teacherId})" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        deleteTeacher(teacher.teacherId).then(() => {
          this.$message.success('教师删除成功')
          // 重新获取教师列表
          if (this.deptFilter) {
            this.fetchTeachersByDept(this.deptFilter)
          } else {
            this.fetchTeachers()
          }
        }).catch(error => {
          console.error('删除教师失败:', error)
          this.$message.error('删除教师失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 显示重置密码对话框
    showResetPasswordDialog(teacher) {
      this.passwordDialog.teacherId = teacher.teacherId
      this.passwordForm = {
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordDialog.visible = true
    },
    
    // 重置教师密码
    handleResetPassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.passwordDialog.loading = true
          
          updateTeacherPassword(this.passwordDialog.teacherId, this.passwordForm.newPassword).then(() => {
            this.$message.success('密码重置成功')
            this.passwordDialog.visible = false
          }).catch(error => {
            console.error('重置密码失败:', error)
            this.$message.error('重置密码失败')
          }).finally(() => {
            this.passwordDialog.loading = false
          })
        } else {
          return false
        }
      })
    },
    
    // 处理表单提交
    handleSubmit() {
      this.$refs.teacherForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          
          // 创建要提交的数据对象
          const teacherData = { ...this.teacherForm }
          
          // 如果是编辑模式，删除confirmPassword字段
          if (this.dialog.type === 'edit') {
            delete teacherData.confirmPassword
            delete teacherData.password
            
            // 调用更新API
            updateTeacher(teacherData.teacherId, teacherData).then(() => {
              this.$message.success('教师信息更新成功')
              this.dialog.visible = false
              
              // 重新获取教师列表
              if (this.deptFilter) {
                this.fetchTeachersByDept(this.deptFilter)
              } else {
                this.fetchTeachers()
              }
            }).catch(error => {
              console.error('更新教师失败:', error)
              this.$message.error('更新教师失败')
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            // 添加模式，删除confirmPassword字段
            delete teacherData.confirmPassword
            
            // 自动生成工号（院系编号+教师数量）
            if (teacherData.deptNumber) {
              teacherData.teacherId = this.previewTeacherId
            } else {
              this.$message.error('请选择所属院系')
              this.submitLoading = false
              return false
            }
            
            // 调用添加API
            addTeacher(teacherData).then(() => {
              this.$message.success('教师添加成功')
              this.dialog.visible = false
              
              // 重新获取教师列表并更新计数
              if (this.deptFilter) {
                this.fetchTeachersByDept(this.deptFilter)
              } else {
                this.fetchTeachers()
              }
            }).catch(error => {
              console.error('添加教师失败:', error)
              this.$message.error('添加教师失败')
            }).finally(() => {
              this.submitLoading = false
            })
          }
        } else {
          this.$message.error('表单验证失败，请检查输入')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
/* 教师管理页面容器样式：设置内边距 */
.teachers-container {
  padding: 20px;
}

/* 页面标题和工具栏样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 页面标题样式 */
.page-header h2 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

/* 工具栏样式：设置按钮和搜索框布局 */
.toolbar {
  display: flex;
  align-items: center;
}

/* 过滤器样式 */
.filter-box {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  color: #606266;
}

/* 表格样式：设置上边距 */
.el-table {
  margin-top: 20px;
}

/* 分页控件容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: right;
}

/* 表单样式 */
.teacher-form .el-form-item {
  margin-bottom: 18px;
}

/* 确保所有el-select与el-input宽度一致 */
.teacher-form .el-select {
  width: 100%;
}

/* 工号提示样式 */
.teacher-id-hint {
  background-color: #ecf8ff;
  padding: 10px 15px;
  border-radius: 4px;
  margin-top: 10px;
  margin-bottom: 10px;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.teacher-id-hint i {
  margin-right: 8px;
  font-size: 16px;
}

.teacher-id-hint strong {
  margin-left: 4px;
}
</style>